package hos.net.soap

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

/**
 * <p>Title: SoapConvertUtils </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-04-09 20:26
 * @version : 1.0
 */
object SoapConvertUtils {

    @JvmStatic
    fun parseJsonObject(json: JSONObject): MutableMap<String, Any?> {
        val map = mutableMapOf<String, Any?>()
        val rootKey = json.keys()
        //迭代是反复内容,使用循环实现,循环的条件,集合中没元素, hasNext()返回了false
        while (rootKey.hasNext()) {
            val key = rootKey.next()
            try {
                when (val value = json[key]) {
                    is JSONObject -> {
                        map[key] = parseJsonObject(value)
                    }

                    is JSONArray -> {
                        map[key] = parseJsonArray(value)
                    }

                    else -> {
                        map[key] = value
                    }
                }
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        return map
    }

    @JvmStatic
    fun parseJsonArray(json: JSONArray): MutableList<Any?> {
        val list = mutableListOf<Any?>()
        val length = json.length()
        for (i in 0 until length) {
            try {
                val value = json[i]
                if (value is JSONObject) {
                    list.add(parseJsonObject(value))
                } else {
                    list.add(value)
                }
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        return list
    }

    @Throws(JSONException::class)
    fun parseMap(json: String): MutableMap<String, Any?> {
        return parseJsonObject(JSONObject(json))
    }

    @Throws(JSONException::class)
    fun parseList(json: String): MutableList<Any?> {
        return parseJsonArray(JSONArray(json))
    }

    @Throws(JSONException::class)
    fun parse(json: String): Any {
        return if (json.startsWith("{") && json.endsWith("}")) {
            parseMap(json)
        } else {
            parseList(json)
        }
    }
}